<?php
namespace app\admin\controller\config;

use app\admin\BaseController;
use app\lib\exception\FailedException;
use app\Validate\FreightValidate;
use think\Request;


class Freight extends BaseController
{
    protected $model = '';

    public function initialize()
    {
        $this->model = new \app\admin\model\Freight();
    }

    /**
     * 运费的基础配置
     * @return \think\response\Json
     */
    public function freightConfig(){
        $config = (new \app\admin\model\Config())->getConfigKey();
        $freight = (new \app\admin\model\Freight())->selectListWith("p_name,c_name,a_name",[],"*","min_km");
        $returnList = [
            'freight_type'=>$config['freight_type'],
            'freight_price'=>$config['freight_price'],
            'freight_center'=>$config['freight_center'],
            'freight'      =>$freight
        ];
        return writeJson(200,$returnList);
    }

    /**
     * 运费模板的修改
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws FailedException
     */
    public function freightEdit(Request $request){
        (new FreightValidate())->gocheck();
        $post = $request->post();
        (new \app\admin\model\Config())->where('k','freight_type')->setField("v",$post['freight_type']);
        (new \app\admin\model\Config())->where('k','freight_price')->setField("v",$post['freight_price']);
        (new \app\admin\model\Config())->where('k','freight_center')->setField("v",$post['freight_center']);
        (new \app\admin\model\Freight())->where([['id','gt',0]])->delete();
        $new = [];
        foreach ($post['freight'] as $value){
            $new[] =[
                'province_id'=>$value['province_id'],
                'city_id'  =>$value['city_id'],
                'area_id'  =>$value['area_id'],
                'min_unit' =>$value['min_unit'], //最小订单金额区间
                'max_unit' =>$value['max_unit'], //最大订单金额区间
                'min_km' =>$value['min_km'], //最小订单金额区间
                'max_km' =>$value['max_km'], //最大订单金额区间
                'price'    =>$value['price'],    //运费价格
                'remarks'  =>$value['remarks'],  //抬头
                'create_time'=>time()
            ];
        }
        $res = (new \app\admin\model\Freight())->saveAll($new);
        if(!$res){
            throw new FailedException(['msg'=>'操作失败']);
        }
        return writeJson(200,[]);
    }
}
